package com.bjb.vr.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.bjb.vr.common.result.BaseErrorCode;
import com.bjb.vr.common.result.CommonResult;
import com.bjb.vr.common.utils.JwtTokenUtil;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

/**
 * @author hujingbo
 * @version 1.0.0
 * @Description
 * @createTime 2022年03月04日 11:09
 */
@Component
@Data
public class WebsocketAccessFilter implements GlobalFilter, Ordered {


    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE + 12;
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String url = exchange.getRequest().getURI().getPath();

        if (!url.startsWith("/ws/")) {
            return chain.filter(exchange);
        }

        //从请求头中取得token
        String token = (String) exchange.getRequest().getQueryParams().getFirst("token");
        if (StringUtils.isEmpty(token)) {
            ServerHttpResponse response = getServerHttpResponse(exchange);
            byte[] responseByte = JSON.toJSONString(CommonResult.Fail(BaseErrorCode.UNAUTHORIZED)).getBytes();
            DataBuffer dataBuffer = response.bufferFactory().wrap(responseByte);
            return response.writeWith(Flux.just(dataBuffer));
        }

        //判断请求中的token是否有效
        CommonResult result = JwtTokenUtil.validateJWT(token);
        boolean verifyResult = result.isSuccess();
        if (!verifyResult) {
            ServerHttpResponse response = getServerHttpResponse(exchange);
            byte[] responseByte = JSON.toJSONString(CommonResult.Fail(BaseErrorCode.UNAUTHORIZED)).getBytes();
            DataBuffer buffer = response.bufferFactory().wrap(responseByte);
            return response.writeWith(Mono.just(buffer));
        }
        return chain.filter(exchange);
    }

    /**
     * 封装Response响应
     *
     * @param exchange
     * @return
     */
    private ServerHttpResponse getServerHttpResponse(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.OK);
        response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON.toString());
        return response;
    }
}
